package com.witmore.neutron.ai.mcp.server.trading.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.witmore.neutron.ai.mcp.server.trading.db.entity.ScorpionStockAbnormalRecordDO;
import com.witmore.neutron.ai.mcp.server.trading.db.mapper.ScorpionStockAbnormalRecordMapper;
import com.witmore.neutron.ai.mcp.server.trading.service.AbnormalReportService;
import com.witmore.neutron.ai.mcp.server.trading.service.AbnormalPdfReportService;
import com.witmore.neutron.ai.mcp.server.trading.service.OssUploadService;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import java.io.ByteArrayOutputStream;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 异动报告服务实现类
 * 
 * @author 豆子高
 * @since 2025-01-27
 */
@Slf4j
@Service
public class AbnormalReportServiceImpl implements AbnormalReportService {

    @Autowired
    private ScorpionStockAbnormalRecordMapper abnormalRecordMapper;

    @Autowired
    private AbnormalPdfReportService abnormalPdfReportService;

    @Autowired
    private OssUploadService ossUploadService;

    @Override
    @Async
    public void generateAbnormalReportAsync(Long recordId, Long userId, String stockCode, String stockName) {
        log.info("开始异步生成异动报告 - 记录ID: {}, 用户ID: {}, 股票代码: {}, 股票名称: {}", 
                recordId, userId, stockCode, stockName);
        
        try {
            // 默认只生成PDF格式的报告
            String pdfReportUrl = generatePdfReport(recordId, userId, stockCode, stockName);
            
            // 更新数据库记录，保存报告信息
            if (pdfReportUrl != null) {
                updateAbnormalRecordWithReport(recordId, "pdf", pdfReportUrl);
                log.info("异动报告生成完成 - 记录ID: {}, PDF报告: {}", recordId, pdfReportUrl);
            } else {
                log.warn("PDF报告生成失败 - 记录ID: {}", recordId);
            }
            
        } catch (Exception e) {
            log.error("异步生成异动报告失败 - 记录ID: {}, 用户ID: {}, 股票代码: {}", 
                    recordId, userId, stockCode, e);
        }
    }

    @Override
    public String generatePdfReport(Long recordId, Long userId, String stockCode, String stockName) {
        log.info("生成PDF异动报告 - 记录ID: {}, 股票代码: {}", recordId, stockCode);
        
        try {
            // 根据记录ID查询异动记录
            ScorpionStockAbnormalRecordDO record = abnormalRecordMapper.selectById(recordId);
            if (record == null) {
                log.warn("未找到异动记录 - 记录ID: {}", recordId);
                return null;
            }

            // 解析异动数据
            String abnormalDataJson = record.getAbnormalData();
            String stockBasicInfoJson = record.getStockBasicInfo();
            
            if (abnormalDataJson == null || stockBasicInfoJson == null) {
                log.warn("异动记录数据不完整 - 记录ID: {}", recordId);
                return null;
            }

            log.info("开始生成基于数据库记录的PDF报告 - 记录ID: {}", recordId);
            
            // 使用统一的PDF生成接口（基于数据库记录）
            byte[] pdfBytes = abnormalPdfReportService.generateAbnormalReportPdfFromRecord(
                    userId, stockCode, abnormalDataJson, stockBasicInfoJson);
            
            if (pdfBytes != null && pdfBytes.length > 0) {
                // 上传到OSS并获取完整URL
                String pdfUrl = ossUploadService.uploadStockAnalysisReport(pdfBytes, stockCode, userId);
                log.info("PDF报告生成并上传成功 - 记录ID: {}, 报告URL: {}", recordId, pdfUrl);
                return pdfUrl;
            } else {
                log.warn("PDF报告生成失败 - 记录ID: {}", recordId);
                return null;
            }
            
        } catch (Exception e) {
            log.error("生成PDF异动报告失败 - 记录ID: {}, 股票代码: {}", recordId, stockCode, e);
            return null;
        }
    }



    @Override
    public String generateExcelReport(Long recordId, Long userId, String stockCode, String stockName) {
        log.info("Excel异动报告生成 - 记录ID: {}, 股票代码: {} （当前为空实现）", recordId, stockCode);
        
        // TODO: Excel报告生成功能暂未实现，当前为空实现
        log.warn("Excel报告生成功能暂未实现 - 记录ID: {}, 股票代码: {}", recordId, stockCode);
        
        return null;
    }

    /**
     * 更新异动记录的报告信息
     * 
     * @param recordId 记录ID
     * @param reportType 报告类型
     * @param reportUrl 报告URL
     */
    private void updateAbnormalRecordWithReport(Long recordId, String reportType, String reportUrl) {
        try {
            if (recordId == null || reportUrl == null) {
                log.warn("更新异动记录报告信息参数无效 - 记录ID: {}, 报告URL: {}", recordId, reportUrl);
                return;
            }

            LambdaUpdateWrapper<ScorpionStockAbnormalRecordDO> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(ScorpionStockAbnormalRecordDO::getId, recordId)
                    .set(ScorpionStockAbnormalRecordDO::getAbnormalReportType, reportType)
                    .set(ScorpionStockAbnormalRecordDO::getAbnormalReportAttachmentUrl, reportUrl)
                    .set(ScorpionStockAbnormalRecordDO::getUpdateTime, LocalDateTime.now());

            int updateCount = abnormalRecordMapper.update(null, updateWrapper);
            
            if (updateCount > 0) {
                log.info("更新异动记录报告信息成功 - 记录ID: {}, 报告类型: {}, 报告URL: {}", 
                        recordId, reportType, reportUrl);
            } else {
                log.warn("更新异动记录报告信息失败，未找到对应记录 - 记录ID: {}", recordId);
            }
            
        } catch (Exception e) {
            log.error("更新异动记录报告信息异常 - 记录ID: {}, 报告类型: {}, 报告URL: {}", 
                    recordId, reportType, reportUrl, e);
        }
    }
}
